<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import { computed, ref, watch } from 'vue';

import { DictEnum } from '@vben/constants';

import { message } from 'ant-design-vue';

import { customerTransferApi } from '#/api/hm/customer/transfer';
import { DictTag } from '#/components/dict';
import { getDictOptions } from '#/utils/dict';

// Props
interface Props {
  visible: boolean;
  staffInfo?: any;
  activeStaffList: any[];
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
});

// Emits
const emit = defineEmits<{
  success: [];
  'update:visible': [value: boolean];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const formData = ref({
  fromStaffName: '',
  customerCount: '',
  toStaffId: undefined,
  transferReason: '',
});

const modalVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const staffOptions = computed(() =>
  props.activeStaffList.map((staff) => ({
    label: staff.nickName,
    value: staff.userId,
  })),
);

const previewColumns = [
  { title: '客户姓名', dataIndex: 'customerName', key: 'customerName' },
  { title: '电话', dataIndex: 'phone', key: 'phone' },
  {
    title: '会员等级',
    dataIndex: 'memberLevel',
    key: 'memberLevel',
  },
];

const rules = {
  toStaffId: [{ required: true, message: '请选择新负责员工' }],
  transferReason: [{ required: true, message: '请输入迁移原因' }],
};

// 监听员工信息变化
watch(
  () => props.staffInfo,
  (newVal) => {
    if (newVal) {
      formData.value.fromStaffName = newVal.nickName;
      formData.value.customerCount = `${newVal.customerCount}个`;
    }
  },
  { immediate: true },
);

// 方法
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    const transferData = {
      customerIds: props.staffInfo.customerList.map((c: any) => c.customerId),
      toStaffId: formData.value.toStaffId,
      transferReason: formData.value.transferReason,
      oldStaffName: props.staffInfo.nickName,
    };
    console.log(transferData);

    await customerTransferApi.batchTransferCustomers(transferData);
    message.success('批量迁移成功');
    emit('success');
    handleCancel();
  } catch {
    message.error('迁移失败，请重试');
  }
};

const handleCancel = () => {
  formRef.value?.resetFields();
  modalVisible.value = false;
};
</script>

<template>
  <a-modal
    v-model:visible="modalVisible"
    title="批量迁移客户"
    width="800px"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="原负责员工" name="fromStaffName">
            <a-input v-model:value="formData.fromStaffName" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="客户数量" name="customerCount">
            <a-input v-model:value="formData.customerCount" disabled />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="选择新负责员工" name="toStaffId">
        <a-select
          v-model:value="formData.toStaffId"
          placeholder="请选择新负责员工"
          :options="staffOptions"
        />
      </a-form-item>

      <a-form-item label="迁移原因" name="transferReason">
        <a-textarea
          v-model:value="formData.transferReason"
          placeholder="请输入迁移原因"
          :rows="3"
        />
      </a-form-item>

      <!-- 客户列表预览 -->
      <a-form-item label="待迁移客户列表">
        <a-table
          :columns="previewColumns"
          :data-source="staffInfo?.customerList"
          :pagination="false"
          size="small"
          :scroll="{ y: 300 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'memberLevel'">
              <DictTag
                v-if="record.memberLevel"
                :dicts="getDictOptions(DictEnum.SYS_MEMBER_LEVEL)"
                :value="record[column.key]"
              />
              <span v-else>-</span>
            </template>
          </template>
        </a-table>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
